<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i> 我的题库
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="handle-box">
                <el-input v-model="query.name" placeholder="题库名称" class="handle-input mr10"></el-input>
                <el-button type="primary" icon="el-icon-search" @click="handleSearch">
                    搜索
                </el-button>
            </div>
            <div class="control-box clearfix" style="margin-bottom: 20px;">
                <div class="float-left" style="float: left">
                    <el-button type="primary" icon="el-icon-plus" class="handle-del mr10"
                        @click="dialogFormVisible = true">添加</el-button>
                    <el-button type="danger" plain icon="el-icon-delete" class="handle-del mr10"
                        @click="delAllSelection">删除</el-button>
                </div>
                <div class="float-right" style="float: right">
                    <el-button type="primary" icon="el-icon-plus" plain class="handle-del mr10"
                        @click="topicLibPublishFunc">
                        <i></i>
                        <span>发布</span>
                    </el-button>
                </div>
                <div style="clear:both;"></div>
            </div>
            <el-table :data="tableData" border class="table" ref="multipleTable" header-cell-class-name="table-header"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center"></el-table-column>
                <el-table-column prop="topic_lib_name" label="题库名称"></el-table-column>
                <el-table-column prop="topic_single_count" label="单选题数量"></el-table-column>
                <el-table-column prop="topic_multi_count" label="多选题数量"></el-table-column>
                <el-table-column prop="topic_judge_count" label="判断题数量"></el-table-column>
                <el-table-column label="考试时长">
                    <template slot-scope="scope">
                        <span>{{ scope.row.exam_time }}</span>分钟
                    </template>
                </el-table-column>
                <el-table-column prop="exam_limit" label="考试时间"></el-table-column>
                <el-table-column prop="exam_fullcredit" label="考试满分"></el-table-column>
                <el-table-column prop="exam_passline" label="及格线"></el-table-column>
                <el-table-column label="是否通过" align="center">
                    <template slot-scope="scope">
                        <el-tag
                            :type="scope.row.topic_ispublish == 1 ? 'success' : (scope.row.topic_ispublish == null ? 'info' : '')">{{
                                scope.row.topic_ispublish
                                == 1 ? '已发布' : '未发布' }}</el-tag>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top:20px;">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="5"
                    layout="total, sizes, prev, pager, next, jumper" :total="pageTotal">
                </el-pagination>
            </div>
        </div>

        <el-dialog title="创建题库" :visible.sync="dialogFormVisible">
            <el-form :model="ruleForm">
                <el-form-item label="题库名称" :label-width="formLabelWidth">
                    <el-input v-model="ruleForm.topic_lib_name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="单选题数量" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.topic_single_count" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="多选题数量" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.topic_multi_count" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="判断题数量" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.topic_judge_count" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="考试时长" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.exam_time" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="考试时间" :label-width="formLabelWidth">
                    <el-select v-model="ruleForm.exam_limit" placeholder="选择考试时间限制">
                        <el-option label="限时" value="限时"></el-option>
                        <el-option label="不限时" value="不限时"></el-option>
                    </el-select>
                </el-form-item>


                <el-form-item label="考试总分" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.exam_fullcredit" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="及格线" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.exam_passline" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="考试类型" :label-width="formLabelWidth">
                    <el-select v-model="ruleForm.exam_type" placeholder="请选择考试类型">
                        <el-option label="完成公开" value="完成公开"></el-option>
                        <el-option label="不公开" value="不公开"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="题库数量" :label-width="formLabelWidth">
                    <el-input type="number" v-model="ruleForm.topic_count" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { topicLibAdd, topicLibList, topicLibTotal2, topicLibPublish, topicLibSearch, topicLibDelete } from '../../api/index';
export default {
    name: 'mytopicmanagement',
    data() {
        return {
            query: {
                name: '',
                pageIndex: 1,
                pageSize: 5
            },
            delList: [],
            // editVisible: false,
            pageTotal: 0,
            all: 0,
            idx: -1,
            id: -1,
            currentPage: 1,
            // 是否显示弹窗
            dialogFormVisible: false,
            // 表单信息
            ruleForm: {
                topic_lib_name: '',
                topic_count: 10,
                topic_single_count: 4,
                topic_multi_count: 2,
                topic_judge_count: 4,
                exam_time: 30,
                exam_type: '完成公开',
                exam_limit: '限时',
                exam_fullcredit: 100,
                exam_passline: 60,
            },
            // label标签宽度
            formLabelWidth: '120px',
            // 记录题库的数组
            tableData: [],
            // 多选
            multipleSelection: [],
            // 被删除题库
            topicLibDeleteArr: [],
            // 被发布题库
            topicPublishArr: []
        };
    },
    computed: {
        total() {
            let num1 = this.ruleForm.topic_single_count - 0;
            let num2 = this.ruleForm.topic_multi_count - 0;
            let num3 = this.ruleForm.topic_judge_count - 0;
            return num1 + num2 + num3;
        }
    },
    watch: {
        total(val) {
            this.ruleForm.topic_count = val;
        }
    },
    created() {
        this.getData();
        this.addTotal();
    },
    methods: {
        handleSizeChange(val) {
            // console.log(`每页 ${val} 条`);
            this.getData(val);
        },
        handleCurrentChange(val) {
            // console.log(`当前页: ${val}`);
            this.getData(val);
        },
        // 获取题库列表
        getData(page_num = 1, page_size = 5) {
            topicLibList({ page_num, page_size })
                .then(content => {
                    // console.log('题库列表:', content)
                    let { code, result } = content;
                    if (code == 200) {
                        this.tableData = result;
                    }
                })
                .catch(
                    err => {
                        console.log(err)
                    }
                )

        },
        // 获取总数
        addTotal() {
            // 获取token
            topicLibTotal2({}).then(content => {
                // console.log('总数:', content)
                if (content.code == 200) {
                    this.pageTotal = content.total || 10;
                    // this.all = content.total || 10;
                }
            })
        },
        // 触发搜索按钮
        handleSearch() {
            this.$set(this.query, 'pageIndex', 1);
            // console.log(this.query.name);
            this.addSearch(this.query.name);
        },
        // 搜索题库
        async addSearch(keyword) {
            await topicLibSearch({ keyword }).then(content => {
                // console.log('题库列表:', content)
                let { code, result } = content;
                if (code == 200) {
                    this.tableData = result;
                }
            })
                .catch(
                    err => {
                        console.log(err)
                    }
                )

        },
        // 多选操作
        handleSelectionChange(val) {
            this.multipleSelection = val;
            // console.log({val})
            this.topicLibDeleteArr = val;
            this.topicPublishArr = val;
        },
        // 删除题库
        async delAllSelection() {
            const length = this.multipleSelection.length;
            let str = '';
            this.delList = this.delList.concat(this.multipleSelection);
            for (let i = 0; i < length; i++) {
                str += this.multipleSelection[i].name + ' ';
            }
            // this.$message.error(`删除了${str}`);
            if (confirm('您确定删除该题库吗?')) {
                // 执行删除
                for (let i = 0; i < this.topicLibDeleteArr.length; i++) {
                    await topicLibDelete({ topic_lib_id: this.topicLibDeleteArr[i].topic_lib_id }).then(row => {
                        if (row.code == 200) {
                            // console.log(row);
                            let arr = this.tableData.filter(item => {
                                if (item.topic_lib_id != this.topicLibDeleteArr[i].topic_lib_id) {
                                    return item;
                                }
                            })
                            this.tableData = arr;
                        }
                    })
                }
            }

            this.multipleSelection = [];
        },
        // 分页导航
        handlePageChange(val) {
            this.$set(this.query, 'pageIndex', val);
            this.getData(val);
        },
        // 添加题库
        async submitForm() {
            let { topic_lib_name, topic_count, topic_single_count, topic_multi_count, topic_judge_count, exam_time, exam_type, exam_limit, exam_fullcredit, exam_passline } = this.ruleForm;
            // console.log({topic_lib_name, topic_count, topic_single_count, topic_multi_count, topic_judge_count, exam_time, exam_type})
            // 判断输入框是否有值
            if (topic_lib_name.length == 0 || exam_time.length == 0 || exam_type.length == 0 || exam_time == 0) {
                this.$message({
                    message: '题库名称、考试类型不能为空。',
                    type: 'warning'
                })
                return false;
            }
            // 调用添加
            await topicLibAdd({ topic_lib_name, topic_count, topic_single_count, topic_multi_count, topic_judge_count, exam_time, exam_type, exam_limit, exam_fullcredit, exam_passline })
                .then(content => {
                    // console.log('添加:', content);
                    if (content.code == 200) {
                        this.$message({
                            message: content.msg,
                            type: 'success'
                        })
                        this.dialogFormVisible = false;
                        // 初始化数据
                        this.getData();
                        this.addTotal();
                        // 重置表单
                        this.ruleForm.topic_lib_name = '';
                    } else {
                        this.$message({
                            message: content.msg,
                            type: 'warning'
                        })
                        if (content.msg == '登录已过期,请重新登录') {
                            this.$router.push({
                                path: '/login'
                            })
                        }
                    }
                })
                .catch(err => {
                    console.log(err)
                })
        },
        // 发布题库
        async topicLibPublishFunc() {
            if (this.topicPublishArr.length == 0) {
                return false;
            }
            if (confirm('是否确定发布该题库。')) {
                // 执行发布
                for (let i = 0; i < this.topicPublishArr.length; i++) {
                    await topicLibPublish({ topic_lib_id: this.topicPublishArr[i].topic_lib_id }).then(row => {
                        console.log("发布：", row);
                        if (row.code == 200) {
                            // console.log(row);
                            let arr = this.tableData.map(item => {
                                if (item.topic_lib_id == this.topicPublishArr[i].topic_lib_id) {
                                    item.topic_ispublish = 1;
                                    return item;
                                } else {
                                    return item;
                                }
                            })
                            this.tableData = arr;
                        }
                    })
                }
            }

        }
    }
};
</script>

<style scoped>
.handle-box {
    margin-bottom: 20px;
}

.handle-select {
    width: 120px;
}

.handle-input {
    width: 300px;
    display: inline-block;
}

.table {
    width: 100%;
    font-size: 14px;
}

.red {
    color: #ff0000;
}

.mr10 {
    margin-right: 10px;
}

.table-td-thumb {
    display: block;
    margin: auto;
    width: 40px;
    height: 40px;
}
</style>
